package com.yexx.logger.filter;

import com.yexx.logger.properties.TraceProperties;
import org.slf4j.MDC;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.Filter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static com.yexx.core.constant.CommonConstants.LOG.*;

/**
 * Description: 日志跟踪过滤器
 *
 * @author: zuomin (myleszelic@outlook.com)
 * @date: 2020/12/07-11:56
 */
@ConditionalOnClass(Filter.class)
public class TraceFilter extends OncePerRequestFilter {

    @Resource
    private TraceProperties traceProperties;

    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
        return !traceProperties.getEnable();
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, javax.servlet.FilterChain filterChain) throws ServletException, IOException {
        try {
            String traceId = null;
            String traceIdHeader = request.getHeader(TRACE_ID_HEADER);
            String traceIdAttr = (String) request.getAttribute(TRACE_ID_ATTR);
            String userIdHeader = request.getHeader(USER_ID_HEADER);
            if (!StringUtils.isEmpty(traceIdHeader)) {
                traceId = traceIdHeader;
            }
            if (!StringUtils.isEmpty(traceIdAttr)) {
                traceId = traceIdAttr;
            }
            if (!StringUtils.isEmpty(traceId)) {
                MDC.put(LOG_TRACE_ID, traceId);
            }
            if (!StringUtils.isEmpty(userIdHeader)) {
                MDC.put(LOG_USER_ID, userIdHeader);
            }
            filterChain.doFilter(request, response);
        } finally {
            MDC.remove(LOG_TRACE_ID);
        }
    }
}
